package cn.nyse.ktc_spit.service;

import cn.nyse.ktc_spit.dao.SpitDao;
import cn.nyse.ktc_spit.dao.ThumbupDao;
import cn.nyse.ktc_spit.entity.Spit;
import cn.nyse.ktc_spit.entity.Thumbup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.List;

@Service
public class SpitServiceImpl implements SpitService{

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private ThumbupDao thumbupDao;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Spit spit) {
        spitDao.save(spit);
    }

    @Override
    public List<Spit> findAllPage() {
        return spitDao.findAll();
    }

    @Override
    public List<Spit> findBySpitId(String spitId) {
        return spitDao.findByUserid(spitId);
    }

    @Override
    public void updateSpit(String spitId, String userid) {
        Thumbup thumbup = thumbupDao.findByUseridAndSpitid(userid, spitId);
        int inc=1;
        if (thumbup!=null){
            inc=-1;
            thumbupDao.deleteById(thumbup.getId());
        }else {
            thumbup=new Thumbup();
            thumbup.setSpitid(spitId);
            thumbup.setUserid(userid);
            thumbupDao.save(thumbup);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is("1232585866992541696"));
        Update update = new Update();
        update.inc("thumbup",inc);
        mongoTemplate.updateFirst(query,update,Spit.class);
    }

    @Override
    public List<Spit> searchByCondition(Spit spit) {
        Example<Spit> example = Example.of(spit);
        return spitDao.findAll(example);
    }

    @Override
    public Page<Spit> findSpitPage(int page, int size, Spit spit) {
        return spitDao.findAll(PageRequest.of(page-1,size));
//        return null;
    }

    @Override
    public Page<Spit> findByParentid(String parentid, int page, int size) {
        return spitDao.findByParentid(parentid, PageRequest.of(page-1,size));
    }
}
